<script setup lang="ts">
import { reactive, ref } from 'vue'
import { reqAttrList } from '@/api/product/attr'
import { reqSpuImageList, reqSpuSaleAttrList } from '@/api/product/spu'
import { reqAddSku } from '@/api/product/sku'
import { ElMessage } from 'element-plus'
import type { ResponseData } from '@/api/type.ts'
import type { Attr } from '@/api/product/attr/type.ts'
import type { SPU, spuImage, spuSaleAttr } from '@/api/product/spu/type.ts'
import type { SKU } from '@/api/product/sku/type.ts'

defineProps({
  scene: Number,
})

const $emit = defineEmits(['update:scene'])

const attrList = ref<Attr[]>([])
const saleAttrList = ref<spuSaleAttr[]>([])
const imageList = ref<spuImage[]>([])

const sku = reactive<SKU>({
  category3Id: '',
  skuName: '',
  spuId: '',
  tmId: '',
  price: '',
  weight: '',
  skuDesc: '',
  isSale: 0,
  skuDefaultImg: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuImageList: [],
})

const imagesTableRef = ref<any>()

const initSku = (c1Id: number, c2Id: number, c3Id: number, spu: SPU) => {
  // 获取平台数据
  getAttrList(c1Id, c2Id, c3Id)
  // 获取spu销售属性
  getSaleAttrList(spu?.id as number)
  // 获取spu图片
  getSpuImgList(spu?.id as number)

  sku.category3Id = spu?.category3Id as number
  sku.spuId = spu?.id as number
  sku.tmId = spu?.tmId as number
}

const getAttrList = async (c1Id: number, c2Id: number, c3Id: number) => {
  try {
    const { code, data, message }: ResponseData<Attr[]> = await reqAttrList(
      c1Id,
      c2Id,
      c3Id,
    )
    if (code == 200) {
      attrList.value = data
    } else {
      ElMessage({
        type: 'error',
        message: message,
      })
    }
  } catch (err: any) {
    console.log(err)
    ElMessage({
      type: 'error',
      message: err?.message,
    })
  }
}

const getSaleAttrList = async (spuId: number) => {
  try {
    const { code, data, message }: ResponseData<spuSaleAttr[]> =
      await reqSpuSaleAttrList(spuId)
    if (code == 200) {
      saleAttrList.value = data
    } else {
      ElMessage({
        type: 'error',
        message: message,
      })
    }
  } catch (err: any) {
    console.log(err)
    ElMessage({
      type: 'error',
      message: err?.message,
    })
  }
}

const getSpuImgList = async (spuId: number) => {
  try {
    const { code, data, message }: ResponseData<spuImage[]> =
      await reqSpuImageList(spuId)
    if (code == 200) {
      imageList.value = data
    } else {
      ElMessage({
        type: 'error',
        message: message,
      })
    }
  } catch (err: any) {
    console.log(err)
    ElMessage({
      type: 'error',
      message: err?.message,
    })
  }
}

const onDefaultImg = (row: spuImage) => {
  imagesTableRef.value.clearSelection()
  imagesTableRef.value.toggleRowSelection(row, true)
  sku.skuDefaultImg = row?.imgUrl
}

const onConfirm = async () => {
  sku.skuAttrValueList = attrList.value.reduce((prev: any, cur: any) => {
    if (cur.attrIdAndValueId) {
      // eslint-disable-next-line no-unsafe-optional-chaining
      const [attrId, valueId] = cur.attrIdAndValueId?.split(':')
      prev.push({
        attrId,
        valueId,
      })
    }
    return prev
  }, [])

  sku.skuSaleAttrValueList = saleAttrList.value.reduce(
    (prev: any, cur: any) => {
      if (cur.saleIdAndValueId) {
        // eslint-disable-next-line no-unsafe-optional-chaining
        const [saleAttrId, saleAttrValueId] = cur.saleIdAndValueId?.split(':')
        prev.push({
          saleAttrId,
          saleAttrValueId,
        })
      }

      return prev
    },
    [],
  )

  try {
    const { code, data, message }: ResponseData<any> = await reqAddSku(sku)
    if (code == 200) {
      ElMessage({
        type: 'success',
        message: '添加成功',
      })
      $emit('update:scene', 0)
    } else {
      ElMessage({
        type: 'error',
        message: data ? data : message,
      })
    }
  } catch (err: any) {
    console.log(err)
    ElMessage({
      type: 'error',
      message: err?.message,
    })
  }
}

const onCancel = () => {
  $emit('update:scene', 0)
}

defineExpose({
  initSku,
})
</script>

<template>
  <el-form label-width="100">
    <el-form-item label="sku名称">
      <el-input v-model="sku.skuName" placeholder="请输入名称"></el-input>
    </el-form-item>
    <el-form-item label="价格（元）">
      <el-input v-model="sku.price" type="number"></el-input>
    </el-form-item>
    <el-form-item label="重量（克）">
      <el-input type="number" v-model="sku.weight"></el-input>
    </el-form-item>
    <el-form-item label="sku描述">
      <el-input
        type="textarea"
        v-model="sku.skuDesc"
        placeholder="请输入描述"
      ></el-input>
    </el-form-item>
    <el-form-item label="平台属性">
      <el-form :inline="true" label-width="80">
        <el-form-item
          v-for="attr in attrList"
          :label="attr?.attrName"
          :key="attr?.id as number"
          size="small"
        >
          <el-select v-model="attr.attrIdAndValueId" placeholder="请选择">
            <el-option
              v-for="attrValue in attr?.attrValueList"
              :key="attrValue?.id"
              :label="attrValue?.valueName"
              :value="`${attr?.id}:${attrValue?.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true" label-width="80">
        <el-form-item
          v-for="attr in saleAttrList"
          :label="attr?.saleAttrName"
          :key="attr?.id"
          size="small"
        >
          <el-select v-model="attr.saleIdAndValueId" placeholder="请选择">
            <el-option
              v-for="attrValue in attr?.spuSaleAttrValueList"
              :key="attrValue?.id"
              :label="attrValue?.saleAttrValueName"
              :value="`${attr?.id}:${attrValue?.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片名称">
      <el-table :data="imageList" ref="imagesTableRef" border>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column prop="imgUrl" label="图片">
          <template #default="{ row }">
            <img :src="row?.imgUrl" alt="图片显示失败" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="imgName" label="名称"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="onDefaultImg(row)">
              设为默认
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onConfirm">确认</el-button>
      <el-button @click="onCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss"></style>
